<?php
  /**
   * Zikula Application Framework
   *
   * @link http://www.zikula.org
   * @version $Id: pnuser.php,v 1.1 2009/06/26 05:17:04 chongasem Exp $
   * @license GNU/GPL - http://www.gnu.org/copyleft/gpl.html
   * @author Simon Birtwistle simon@itbegins.co.uk
   * @package Zikula_Docs
   * @subpackage Tour
   */
  
  /**
   * Main user function, simply returnt he tour index page.
   * @author Simon Birtwistle
   * @return string HTML string
   */
   
   
  function IShopUser_user_main() {
      return IShopUser_user_page();
  }

  function IShopUser_user_prerender(&$render){    
    $render->assign('user',   InnoUtil::getUserInfo());      
  }  
  
  function IShopUser_user_page() {
      //$ctrl the class name
      $ctrl    = FormUtil::getPassedValue('ctrl', "Register", 'REQUEST');
      
      //$method the method of request for edit or view enum[ view | form | delete | list | page]
      $func  = FormUtil::getPassedValue('func', 'page' , 'REQUEST');
      
      $render = pnRender::getInstance('IShopUser');
      
      
      //////////////////////////////
      //
      // Create folder when call page openshop
      //
      //////////////////////////////      
      if($ctrl == "openshop"){
        Loader::loadFile('config.php', "modules/IShopUser");
        
        //Create root path
        if(!is_dir(UPLOAD_FILES_MAINPATH)){
          mkdir(UPLOAD_FILES_MAINPATH, 0777);
          
          //copy .htaccess and index.html into resource directory (root path)
          copy(HTACCESS_PATH, UPLOAD_FILES_MAINPATH_HTACCESS_PATH);
          copy(HTML_BLANK_PATH, UPLOAD_FILES_MAINPATH_HTML_BLANK_PATH);          
        }
    
    
        //Create gallery path
        if(!is_dir(UPLOAD_FILES_ISHOPUSER)){
          mkdir(UPLOAD_FILES_ISHOPUSER, 0777);
          
          //copy .htaccess and index.html into resource directory (root path)
          copy(HTACCESS_PATH, UPLOAD_FILES_ISHOPUSER_HTACCESS);
          copy(HTML_BLANK_PATH, UPLOAD_FILES_ISHOPUSER_BLANK_HTML);          
        }   
        
    
        //Create gallery path
        if(!is_dir(UPLOAD_FILES_ISHOPUSER_SHOPICON)){
          mkdir(UPLOAD_FILES_ISHOPUSER_SHOPICON, 0777);
          
          //copy .htaccess and index.html into resource directory (root path)
          copy(HTACCESS_PATH, UPLOAD_FILES_ISHOPUSER_SHOPICON_HTACCESS);
          copy(HTML_BLANK_PATH, UPLOAD_FILES_ISHOPUSER_SHOPICON_BLANK_HTML);          
        }     
        
        
        //Generate user folder    
        $user = InnoUtil::getUserInfo();     
        $userFolder = InnoUtil::encrypt($user['uname'], "phuketinnova");
        
        //Create user folder       
        $userIShopUserImagesPath = UPLOAD_FILES_ISHOPUSER_SHOPICON."/".$userFolder;     
        if(!is_dir($userIShopUserImagesPath)){
          mkdir($userIShopUserImagesPath, 0777);
          
          if(!is_file($userIShopUserImagesPath."/index.html")){
            copy(HTACCESS_PATH, $userIShopUserImagesPath."/.htaccess");
            copy(HTML_BLANK_PATH, $userIShopUserImagesPath."/index.html");           
          }
         
        }  
        $renderIShopUserImagesPath = UPLOAD_FILES_ISHOPUSER_SHOPICON."/".$userFolder."/";         
        $render->assign("upload_path", $renderIShopUserImagesPath);   
      }      
         
      //try to load class
      return $render->fetch('user_'.$func.'_'.strtolower($ctrl).'.htm');
  }
  
  
  //Call Step:1
  function IShopUser_user_register(){
      //$ctrl the class name
      $ctrl    = FormUtil::getPassedValue('ctrl', "Register", 'REQUEST');      
      //$method the method of request for edit or view enum[ view | form | delete | list | page]
      $func  = FormUtil::getPassedValue('func', 'form' , 'REQUEST');      
      $form  = FormUtil::getPassedValue('form', false , 'POST');      


      if (pnModGetVar('Users', 'lowercaseuname', false)) {
          $uname = strtolower($form['uname']);
      }      

      
      //print_r($form); echo "<br>";
      
      $uname        = strtolower(trim($form['uname']));
      $email        = $form['email'];
      $pass         = trim($form['password']);
      $agreetoterms = 1;      
      $user_regdate = DateUtil::getDatetime();

        
      // TODO: add require check for dynamics.
      $checkuser = pnModAPIFunc('Users', 'user', 'checkuser',
                                array('uname'        => $uname,
                                      'email'        => $email,
                                      'agreetoterms' => $agreetoterms
                                )
                   );                                    
                                    
    // if errorcode != 1 then return error msgs
    if ($checkuser != 1) {
        switch ($checkuser)
        {
            case -1:
                $message = 'Sorry! You have not been granted access to this module.';
                break;
            case 2:
                $message =  'Sorry! The e-mail address you entered was incorrectly formatted or is unacceptable for other reasons. Please correct your entry and try again.';
                break;
            case 3:
                $message =  'Error! Please click on the checkbox to accept the site\'s \'Terms of use\' and \'Privacy policy\'.';
                break;
            case 4:
                $message =  'Sorry! The user name you entered is not acceptable. Please correct your entry and try again.';
                break;
            case 5:
                $message =  'Sorry! The user name you entered is too long. The maximum length is 25 characters.';
                break;
            case 6:
                $message =  'Sorry! The user name you entered is reserved and cannot be registered. Please choose another name and try again.';
                break;
            case 7:
                $message =  'Sorry! Your user name cannot contain spaces. Please correct your entry and try again.';
                break;
            case 8:
                $message =  'Sorry! This user name has already been registered. Please choose another name and try again.';
                break;
            case 9:
                $message =  'Sorry! This e-mail address has already been registered, and it cannot be used again for creating another account.';
                break;
            case 11:
                $message =  'Sorry! Your user agent is not accepted for registering an account on this site.';
                break;
            case 12:
                $message =  'Sorry! E-mail addresses from the domain you entered are not accepted for registering an account on this site.';
                break;
            default:
                $message =  'Sorry! You have not been granted access to this module.';
        } // switch

        $render = & pnRender::getInstance('IShopUser');
        $render->assign("error", $message);
        return $render->fetch('user_page_registererror.htm');  
   }

      // TODO: Clean up
      $registered = pnModAPIFunc('Users', 'user', 'finishnewuser',
                                 array('uname'         => $uname,
                                       'pass'          => $pass,
                                       'email'         => $email,
                                       'user_regdate'  => $user_regdate,
                                       'storynum'      => $storynum,
                                       'commentlimit'  => $commentlimit
                                  )
                    ); 
                      
                      
    //Call Step:2                                
     if($registered) {
        //Do the insert extend data        
       $obj = array( 
                     'uid'         => $registered,
                     'firstname'   => $form['firstname'],
                     'lastname'    => $form['lastname'],
                     'mobilephone' => $form['mobilephone'],
                     'gender'      => $form['gender']
                     );
        $result = DBUtil::insertObject($obj, 'ishopuser_information');
        
        //Render display
        //LogUtil::registerStatus('Done! Thanks for registering! Your application has been submitted for approval.');
        //$pnr = & pnRender::getInstance('Users');
        //return $pnr->fetch('users_user_loginscreen.htm');    
        $url = "index.php?module=Users&func=loginscreen"; 
        pnRedirect($url);        
        pnShutDown();
                   
     }else{
        echo "False registration";
     }                             
     exit;                                 

  }
  
  //Call Step:3
  function IShopUser_user_openshop(){
    
    $user = InnoUtil::getUserInfo();
    
    
    //print_r($user); exit;
    if($user['uid']){
      $form  = FormUtil::getPassedValue('form', false , 'POST');   

  
      $obj = array( 
                   'house_no'         => $form['house_no'],     
                   'moo'              => $form['moo'],        
                   'soi'              => $form['soi'],        
                   'road'             => $form['road'],        
                   'village'          => $form['village'],        
                   'tambon'           => $form['tambon'],        
                   'district'         => $form['district'],    
                   'province'         => $form['province'],    
                   'zipcode'          => $form['zipcode'],
                   'shop_name'        => $form['shop_name'],                   
                   'shop_subdomain'   => strtolower($form['shop_subdomain']),
                   'shop_database'    => strtolower($form['shop_subdomain']),                 
                   'shop_description' => $form['shop_description'],
                   'shop_icon'        => $form['shop_icon']
                   );
                   
      $pntables = pnDBGetTables();
      $column   = $pntables['ishopuser_information_column'];
  
      $where    = "WHERE ".$column['uid']." = ".$user['uid'];
      
      DBUtil::updateObject ($obj, 'ishopuser_information', $where);


      $url = "index.php?module=IShopUser&func=page&ctrl=selecttheme"; 
      pnRedirect($url);        
      pnShutDown();
    }else{
        $pnr = &pnRender::getInstance('Users');
        return $pnr->fetch('users_user_loginscreen.htm');        
    }
  } 
  
  //Call Step:4
  function IShopUser_user_settheme(){   
         
    $user = InnoUtil::getUserInfo();    
    if($user['uid']){
      $form  = FormUtil::getPassedValue('form', 'andreas08' , 'POST');   
      $obj = array( 
                   'shop_theme'         => $form['shop_theme']     
                   );
                   
      $pntables = pnDBGetTables();
      $column   = $pntables['ishopuser_information_column'];
  
      $where    = "WHERE ".$column['uid']." = ".$user['uid'];
      
      DBUtil::updateObject ($obj, 'ishopuser_information', $where);

      $url = "index.php?module=IShopUser&func=page&ctrl=agreement"; 
      pnRedirect($url);        
      pnShutDown();
      
    }else{
        $pnr = &pnRender::getInstance('Users');
        return $pnr->fetch('users_user_loginscreen.htm');        
    }
  } 
  
  

  function IShopUser_user_agreement(){   
         
    $user = InnoUtil::getUserInfo();
    
      
    //print_r($user); exit;
    if($user['uid']){
      $object = DBUtil::selectObjectByID('ishopuser_information', $user['uid'], 'uid');  
      $object['uname']         = $user['uname'];
      $object['pass']          = $user['pass'];        
      $object['email']         = $user['email'];
      $object['level']         = $user['level'];         
      $object['hash_method']   = $user['hash_method'];   
      $object['hostname']      = "okalimart.com";                     
      $object['prefix_dbname'] = "okalimar_";            
      $object['dbname']        = $object['prefix_dbname'].$object['shop_subdomain'];         
               
      //print_r($object); exit;
      //Streaming data 
      $data_string = json_encode($object);

      //URL
      //$URL = "http://localhost/iclient/";
      $URL = "http://iclient.okalimart.com/";      
      $URI = "index.php?module=SubdomainCreator&type=admin&func=createClient";    
      $streamLink = $URL.$URI;
           
      // Create a stream
      $opts = array(
        'http'=>array(
           'method' => 'POST',
           'header' => 'Content-Type: application/json' . "\r\n". 'Content-Length: ' . strlen($data_string) . "\r\n",
           'content' => $data_string
        )
      );

      //Create context
      $context = stream_context_create($opts);
      
      //Open the file using the HTTP headers set above                                                                                        
      $jsonResult = file_get_contents($streamLink, false, $context); 

      $result = json_decode($jsonResult);
  
      if($result->response == "success"){
        //echo $result->response;  exit;      
        $url = "http://".$result->domain.".".$object['hostname']; 
        pnRedirect($url);              
      }else{
        //$url = "http://iserver.phuketcity.com"; 
        echo "Error : ".$result->error;     
      }    
      pnShutDown();      
    }else{
        $pnr = &pnRender::getInstance('Users');
        return $pnr->fetch('users_user_loginscreen.htm');        
    }   

  } 
  
    